library Copter;

import "dart:io";
import "package:http_server/http_server.dart";

const HOST = "127.0.0.1";
const PORT = 8080;

const LOG_REQUESTS = true;

void main() {
  HttpServer.bind(HOST, PORT).then((HttpServer server) {
    server.listen(requestReceivedHandler);
  });

  print("Serving the copters on http://${HOST}:${PORT}.");
}

void requestReceivedHandler(HttpRequest request) {
  if (LOG_REQUESTS) {
    print("Request: ${request.method} ${request.uri}");
  }
  
  switch (request.method) {
    case 'GET': 
      dispatch(request);
      break;
    case 'POST': 
      dispatch(request);
      break;
  }
  
}

/**
 * Sample code from http_server somewhere ( :) )in the API Docs
 */
void complete(HttpRequest req, void andThen(HttpRequest req, var body)) {
  HttpResponse res = req.response;
  var body = [];
  req.listen((List<int> buffer) => body.add(buffer),
      onDone: () {
          andThen(req, body);
      },
      onError: print);
}

void handleError(error) {
  print(error);
}

void dispatch(HttpRequest request) {
  request.response.headers.contentType = new ContentType("application", "json", charset: "utf-8");
  if (request.uri.path == '/login') {
    login(request);
  } else if (request.uri.path == '/report') {
    report(request);
  } else if( request.uri.path == '/echo'){
    echo(request);
  } else {
    unknown(request);
  }
}
void echo(HttpRequest req) {
  HttpBodyHandler.processRequest(req).then((HttpBody body) {
    String content = body.body.toString();
    print("The body is: [${content}]");
    req.response.headers.contentType = new ContentType("text", "plain", charset: "utf-8");
    // req.response.headers.contentType = new ContentType("application", "json", charset: "utf-8");
    req.response.statusCode = HttpStatus.CREATED;
    req.response.contentLength = content.length;
    req.response.write(content);
    req.response.close().catchError(print);
  });
}

/**
 * the initial connection from client to server
 */
void login(HttpRequest req) {
  HttpBodyHandler.processRequest(req).then((HttpBody body) {
    print(body.body.runtimeType); // Map
    // TODO PAH convert body.body.toString() to json 
    // call 'Game' object that talks Objects not Json
    // generate result...
    var result = body.toString();
    req.response.headers.add('Access-Control-Allow-Origin', '*');
    // req.response.headers.add('Content-Type', 'text/plain');
    req.response.statusCode = HttpStatus.CREATED;
    req.response.write(result);
    req.response.close();
  });
}

/**
 * A user reporting in 
 */
void report(HttpRequest request) {
  
}

/** 
 * WTF?
 */
void unknown(HttpRequest request) {
  print("generating 404 for ${request.uri}");
  request.response.headers.contentType = new ContentType("text", "plain", charset: "utf-8");
  request.response.statusCode = 404;
  request.response.write("What have you done!");
  request.response.close();
}



